package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.AreaMapper;
import com.indusfo.spc.mapper.SiteMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.Area;
import com.indusfo.spc.pojo.Site;
import com.indusfo.spc.pojo.Warehouse;
import com.indusfo.spc.service.AreaService;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


@Service
public class AreaServiceImpl implements AreaService {

    private  static  final Logger logger = LoggerFactory.getLogger(AreaServiceImpl.class);
    
    @Resource
    private AreaMapper areaMapper;
    @Resource
    private SiteMapper siteMapper;
    @Resource
    private UploadMapper uploadMapper;

    @Override
    public JSONObject selectArea(Area area) {
        List<Area> areaList = null;
        int count = 0;
        try {
            Integer pagesize = area.getPagesize();
            Integer pageindex = area.getPageindex();
            if(pagesize != null && pageindex != null) {
                area.setIncept(pagesize*(pageindex - 1));
            }
            areaList = areaMapper.selectArea(area);
            //查询分页总记录数
            count = areaMapper.countArea(area); //返回查询到的总记录数
            if (areaList.isEmpty()) {
                return JSONObject.oK("没有查询到相关数据", areaList, count);
            }
            return JSONObject.oK("查询成功", areaList, count);
        } catch (
                GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject insertArea(Area area) {
        try {
            if(area.getAreaId()!= null) {
                throw new ParamsErrorException("新增时，不能填写id");
            }
            checkParam(area);
            // 调用存储过程
            int row = areaMapper.insertSelective(area);
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            return JSONObject.oK("新增成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject updateArea(Area area) {
        try {
            if(area.getAreaId()== null) {
                throw new ParamsErrorException("请选择要编辑的区域");
            }
            checkParam(area);
            // 调用存储过程
            int row = areaMapper.updateByPrimaryKeySelective(area);
            if(row == 0) {
                throw new ModifyFailedException("数据编辑失败");
            }
            return JSONObject.oK("编辑成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject definedArea(Long[] areaIds, Integer dataState) {
        try {
            if(dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (areaIds == null  || areaIds.length == 0) {
                throw new ParamsErrorException("区域id不能为空");
            }
            if(dataState == 2 || dataState == 3){
                for(Long areaId : areaIds ) {
                    List<Site> areaList = siteMapper.getByAreaId(areaId.intValue());
                    if(areaList.size() != 0){
                        if(dataState == 2) {
                            throw new ParamsErrorException("区域下有库位,删除失败");
                        } else if(dataState == 3) {
                            throw new ParamsErrorException("区域下有库位,停用失败");
                        }
                    }
                }
            }
            // 执行存储过程
            int row = areaMapper.definedArea(areaIds, dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public String checkNoRepeatExcel(Area area) {
        //区域名称
        String areaName = area.getAreaName();
        //区域编码
        String areaCode = area.getAreaCode();
        //仓库名称
        String warehouseName = area.getWarehouseName();
        Map<String, Warehouse> warehouseMap = uploadMapper.queryWarehouse();
        if(StringUtils.isEmpty(areaName) && StringUtils.isEmpty(areaCode) && StringUtils.isEmpty(warehouseName)){
            return "该行数据为空/删除不彻底";
        }
        if(StringUtils.isEmpty(warehouseName)){
            return "仓库名名称为空";
        }
        if(!warehouseMap.containsKey(warehouseName)){
            return "仓库名称填写错误/不规范";
        }
        area.setWarehouseId(warehouseMap.get(warehouseName).getWarehouseId());
        if(StringUtils.isEmpty(areaCode)){
            return "区域编码为空";
        }
        // 编码不能重复
        Integer depCounts = areaMapper.queryArea(area);
        if (depCounts !=0) {
            return "该区域编码已存在";
        }
        if (area.getAreaCode().getBytes().length > 50) {
            return "区域编码超过规定,长度50";
        }

        if(StringUtils.isEmpty(areaName)){
            return "区域名称为空";
        }
        if (area.getAreaName().getBytes().length > 50) {
            return "区域名称超过规定,长度50";
        }
        // 名称不能重复
        Integer areaCounts = areaMapper.queryAreaName(area);
        if (areaCounts !=0) {
            return "该区域名称已存在";
        }
        return null;
    }

    @Override
    public JSONObject updateListArea(List<Area> areaList) {
        uploadMapper.updateListArea(areaList);
        return null;
    }

    /**
     * 参数校验
     */
    private void checkParam(Area area) {
        if (area.getWarehouseId() == null) {
            throw new ParamsErrorException("请选择仓库");
        }
        if (StringUtils.isEmpty(area.getAreaCode())) {
            throw new ParamsErrorException("请填写区域编码");
        }
        if (area.getAreaCode().getBytes().length > 50) {
            throw new ParamsErrorException("区域编码超过规定,长度50");
        }
        if (StringUtils.isEmpty(area.getAreaName())) {
            throw new ParamsErrorException("请填写区域名称");
        }
        if (area.getAreaName().getBytes().length > 50) {
            throw new ParamsErrorException("区域名称超过规定,长度50");
        }
        // 编码不能重复
        Integer depCounts = areaMapper.queryArea(area);
        if (depCounts !=0) {
            throw new ParamsErrorException("该区域编码已存在");
        }
        // 名称不能重复
        Integer areaCounts = areaMapper.queryAreaName(area);
        if (areaCounts !=0) {
            throw new ParamsErrorException("该区域名称已存在");
        }
    }
    
}
